package com.example.mybatis.interceptors;

        import org.slf4j.Logger;
        import org.slf4j.LoggerFactory;
        import org.springframework.web.servlet.HandlerInterceptor;
        import org.springframework.web.servlet.ModelAndView;

        import javax.servlet.http.HttpServletRequest;
        import javax.servlet.http.HttpServletResponse;
        import javax.servlet.http.HttpSession;
        import java.io.IOException;
        import java.io.PrintWriter;

public class WebCorsInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(WebCorsInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("utf-8");
        String method = request.getMethod();
        String origin = request.getHeader("origin");
        logger.info("method={},origin={}",method,origin);
        //跨域处理
        if(origin!=null){
            response.setHeader("Access-Control-Allow-Origin",origin);
            response.setHeader("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,Content-Disposition");
            response.setHeader("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
            response.setHeader("Access-Control-Allow-Credentials","true");
            response.setHeader("X-Powered-By","Tomcat");
            if("OPTIONS".equals(method)||"GET".equals(method)||"POST".equals(method)||"PUT".equals(method)){
                return true;
            }else{
                return false;
            }
        }else{
            return true;
        }


    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    /**
     * 验证用户是否登录过
     * @param request
     * @param response
     * @return
     */
    private boolean checkLogin(HttpServletRequest request,HttpServletResponse response){
        String uri = request.getRequestURI();
        //如果是登录或注册接口则直接放行
        if(uri.endsWith("/login")||uri.endsWith("/register")){
            return true;
        }
        HttpSession session = request.getSession();
        if(session.getAttribute("userInfo")!=null){
            return  true;
        }
        try {
            PrintWriter printWriter = response.getWriter();
            printWriter.write("用户没有登录，请登录后再进行操作!");
        } catch (IOException e) {
            logger.error("验证登录失败!",e);
        }
        return false;
    }
}
